package com.cn.wanxi.publisher.thread;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @ClassName ThreadsRunMain
 * @Description 线程的入口类
 * @Author JiJiang
 * @Date 2022/9/28 23:04
 * @Version 1.0
 */

public class ThreadsRunMain {


    public static void main(String[] args) {


        RabbitTemplate rabbitTemplate = generateRabbitTemplate();

        Thread tmp;
        for (int i = 0; i < 5; i++) {
            tmp = new SelfThread("自定义线程" + i, rabbitTemplate);
            tmp.start();
        }


    }


    private static RabbitTemplate generateRabbitTemplate() {

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses("127.0.0.1:5672");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        // 如果需要confirm则设置为true
        connectionFactory.setPublisherConfirms(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
//         rabbitTemplate.setConfirmCallback(rabbitConfirmCallback);

        rabbitTemplate.setMandatory(true);
//         rabbitTemplate.setReturnCallback(rabbitReturnCallback);
        //使用单独的发送连接，避免生产者由于各种原因阻塞而导致消费者同样阻塞
        rabbitTemplate.setUsePublisherConnection(true);


        // rabbitTemplate.setChannelTransacted(false);

        // rabbitTemplate.setChannelTransacted(true);
        // rabbitTemplate.send("", );
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println(" ID:" + correlationData);
            if (ack) {//true表示消息发送成功
                System.out.println("消息发送成功");
            } else {
                System.out.println("消息发送失败:" + cause);
            }
        });

        return rabbitTemplate;

    }

}
